<template>
  <div class="login">
    <van-form validate-first class="form" @submit="onSubmit">
      <p class="title">ipackage</p>
      <div class="panel">
        <van-field
          v-model="username"
          label-width="7rem"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          label-width="7rem"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </div>
      <div class="buttons">
        <van-button round block type="info" native-type="submit" class="button">
          登录
        </van-button>
        <van-button
          native-type="button"
          round
          block
          class="button"
          @click="toRegister"
        >
          注册
        </van-button>
      </div>
    </van-form>
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>

<script>
import { doLogin } from 'service/user'
import { __setUser } from 'common/js/user'
export default {
  name: 'login',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    toRegister () {
      this.$router.push({
        path: '/login/register'
      })
    },
    onSubmit () {
      this.$toast.loading({
        duration: 0,
        message: '登录中...',
        forbidClick: true
      })
      doLogin(this.username, this.password)
        .then(data => { this.loadSuc(data) })
        .catch(message => {
          this.$toast.fail({
            message
          })
        })
    },
    loadSuc (data) {
      __setUser(data)
      this.$toast.success({
        message: '登录成功'
      })
      this.$router.push({
        path: '/list'
      })
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~stylus/method"
  .form
    position: absolute
    top: 15%
    width: 100%
    .title
      margin-bottom: 7rem
      font-weight: bold
      font-size: 5rem
      text-align: center
    .panel
      panel()
      margin: 0 2rem
    .buttons
      margin: 4rem 3rem 0
      .button
        margin-top: 1rem
</style>
